/*
* author:xieyayu
* date:20180601
* e-mail:18210854820@163.com
* detail:提交订单详情
* */
new Vue({
    el:'.ZZHT-container',
    data:{
        name:'xyy',
        currentIndex:-1,
       // isDefalt:false,
        billNum:1,
        isAlert:false,
        addList:[],//地址遍历
        province:[],//获取省的列表
        city:[], //获取市区的列表
        area:[],//获取区域列表
        orderList:[],//显示商品的所有条目
        itemAddress:[],//修改地址单条查询数组
        finalCard:{},//最终的地址：1 客户如果选择地址就用客户的地址，2没有选择，选默认地址3，如果没有默认地址就选择第一个地址作为默认地址
        defaultAddress:{},//默认地址
        invoiceClient:'',//发票抬头


        newCityId:0, //修改地址获得新的市id
        newProvinceId:0,//获得新的省ID
        newAreaId:0,//获得新的区域ID
        isShow:false,
        clickCard:{},//点击获得当前的地址item
        addCard:{//修改选中地址item
             userId:localStorage.userId,
            userName:'',
            userPhone:'',
             isDefault:1,
            provinceId:1,
            cityId:0,
            areaId:0
        }
    },

    mounted:function(){
        this.$nextTick(function(){
            this. addressList();
             this.addAddress();
            this.getProductList();

            this.$http.get(SURL+'areas/getAreas',{params:{parentId:this.newProvinceId}}).then(function (res) {
                this.city=res.body.entity;
                // console.log(this.city)

            })




            // this. defaulFreight();

        })
    },
    computed:{
        addobj:function(){
            // var obj=Object.assign({},this.clickCard,this.addCard)
           // console.log(obj)

        },
      allNum:function () {
          var n=0;
         this.orderList.forEach(function (v,i) {
             // console.log(v)
              n+=v.goodsNum

          })
            return n
      },
      allPrice:function () {
          var n=0;
          this.orderList.forEach(function (v,i) {
             n+= v.goodsPrice*v.goodsNum;
          });
          return  parseInt(n)
      },


      defaultPhone:function () {
          var t='';
                    this.addList.forEach(function (v,i) {
                        if(v.isDefault){
                           t=v.userPhone
                        }
                    });
          return t
      },
      defaultName:function () {
          var t='';
                    this.addList.forEach(function (v,i) {
                        if(v.isDefault){
                           t=v.userName
                        }
                    });
          return t
      },
        defaulFreight:function () {
            var t=0;
            this.orderList.forEach(function (v,i) {
               console.log(v)
                v.freight=v.freight==''?0:v.freight;
                t+=parseInt(v.freight)
            });
            return  parseInt(t)
        },
        defaultScore:function () {
            var t=0;
            this.orderList.forEach(function (v,i) {
                t+=v.score
            })
            return t
        },

    },

    methods:{
        //获取地址所有的列表
        addressList:function () {
            var _this=this;
            // _this.addobj();
        // console.log(this.getUrlParam('sktOrdersId'));
           _this.$http.get(SURL+'sktOrders/selectAddressByUserid',{params:{userId:localStorage.userId}}).then(function (res) {
             //  console.log(res)
            if(res.body.messageCode=='200'){
              //  console.log('请求成功')
                res.body.entity.forEach(function (v,i) {

                    if(v.isDefault){
                        _this.$set(v,'isGod',1);
                    }else{
                        _this.$set(v,'isGod',0);
                    }
                });
                _this.addList=res.body.entity;

                _this.getDefault();
                _this.getFreight();
            }
           }).catch(function (res) {

             // layer.alert('网络请求错误，重新刷新')
           })
        },

        //更改地址,创建新的数组保存当前的信息addCard
        //TODO 做的恶心+恶心，有机会简化代码，重新做
        changeAddress:function(item){
            var _this=this;
            _this.isAlert=!_this.isAlert;

            _this.$http.get(SURL+'sktOrders/selectAddressByUserid',{params:{addressId:item.addressId}}).then(function (res) {
              //  console.log(res)
                _this.newCityId=res.body.entity[0].cityId;
                _this.newProvinceId=res.body.entity[0].provinceId;
                _this.newAreaId=res.body.entity[0].areaId;
                _this.addCard.cityId=_this.newCityId;
                _this.addCard.areaId=_this.newAreaId;
            //    console.log(this.addCard.cityId);

                if(res.body.messageCode=='200'){
                    _this.addCard=Object.assign(res.body.entity[0]);
                    // console.log(_this.addCard)


                    //请求市区
                    _this.$http.get(SURL+'areas/getAreas',{params:{parentId:_this.newProvinceId}}).then(function (re) {
                        _this.city=re.body.entity;
                        _this.addCard.cityId=_this.newCityId;
                        //请求区域
                        _this.$http.get(SURL+'areas/getAreas',{params:{parentId:_this.newCityId}}).then(function (r) {
                            _this.area=r.body.entity;
                            _this.addCard.areaId=_this.newAreaId;
                            // console.log(_this.addCard)

                            _this.$http.get(SURL+'areas/getAreas',{params:{parentId:_this.newCityId}}).then(function (ro) {
                                _this.area=ro.body.entity;
                                _this.addCard.areaId=_this.newAreaId;
                                // console.log(_this.addCard)
                            })
                        })

                    })


                }


            }).catch(function (res) {
               // layer.alert('网络请求错误，重新刷新')
            })
        },
        //获取当前默认地址
        getDefault:function(){
            var _this=this;
            this.addList.forEach(function (v,i) {
                if(v.isDefault){
                    _this.defaultAddress=v
                }
            })
        },

        //设为默认地址
        setDefault:function (item) {
            var _this=this;
            _this.addList.forEach(function (v,i) {
                if(v.isDefault){
                    v.isDefault=0
                   _this.$http.get(SURL+'/sktOrders/changeIsDefault',{params:{userId:localStorage.userId,addressId:item.addressId}}).then(function (res) {
                       if(res.body.messageCode=='200'){
                           // layer.alert('更改成功')
                           _this.getDefault()
                       }
                   }).catch(function (res) {
                      // layer.alert('网络请求错误，重新刷新')
                   })

                }
            });
            item.isDefault=!item.isDefault;
        },
        //删除地址
        deleteAddress:function(item){
            var _this=this;
            layer.confirm('你确定要删除？', {
                btn: ['确定', '取消'] //按钮i
            }, function(i) {
                layer.close(i);
                _this.$http.get(SURL+'/sktOrders/deleteAddress',{params:{addressId:item.addressId}}).then(function (res) {
                   //console.log(res);
                   if(res.body.messageCode=='200'){
                       _this.addList.splice(_this.addList.indexOf(item),1)
                       _this.getFreight()
                   }
                });
            },function (i) {
            })
        },
        //请求省列表
        addAddress:function () {
            this.$http.get(SURL+'areas/getAreas',{params:{parentId:0}}).then(function (res) {
                // console.log(res.body.entity)
                this.province=res.body.entity


              //  console.log(this.province)
                this.requestCity()
            })
        },
        //根据省列表请求市区列表
        requestCity:function () {
          //  console.log(this.addCard.provinceId);
            this.$http.get(SURL+'areas/getAreas',{params:{parentId:this.addCard.provinceId}}).then(function (res) {
                this.city=res.body.entity;
                // console.log(this.city)

            })
        },
        //请求区域
        requestArea:function(){
           // console.log(this.cityId)
            this.$http.get(SURL+'areas/getAreas',{params:{parentId:this.addCard.cityId}}).then(function (res) {
                this.area=res.body.entity;
            })
        },

       // 点击添加地址
        alertAddress:function(){
            var _this=this;
          _this.isAlert=!_this.isAlert;

          // console.log(_this.addCard);
          //  console.log(_this.addCard.userAddress)
              for( var v in _this.addCard){
                //  console.log(v)
                  if(v=='userId'){
                    //  alert(1)
                      _this.addCard.userId=localStorage.userId

                  }else if(v=='isDefault'){
                      _this.addCard.isDefault=1
                  } else {
                     _this.addCard[v]='';

                  }
              }

        },
        //如果当前值为undefined 默认显示为空
        addShow:function(val){

            if( val==undefined ||val==null ){
                val=''
            }
            return val
        },


        //添加地址判断是否为空
        isValue:function(item){
           // console.log(item);
            if(item==''||item==undefined){
                layer.msg('请填写正确的内容，否则我们无法准时为你发货')
            }
        },
        //添加地址
        addAddressCard:function () {
            console.log(this.addCard)

                var reg = /^1[0-9]{10}$/,//手机号正则
              flag = reg.test(this.addCard.userPhone); //true

            if(flag){

                if(this.addCard.addressId){//加入当前有addressId就请求更新地址
                    this.$http.get(SURL+'sktOrders/changeAddress',{params:this.addCard}).then(function (res) {
                        if(res.body.messageCode=='200'){
                            layer.alert(res.body.entity);
                            this.isAlert=!this.isAlert;
                            this. addressList();
                        }
                    }).catch(function (res) {
                        layer.alert('网络请求失败，请刷新！！！')
                    })
                }else{  //否则就新加地址

                    this.$http.get(SURL+'sktOrders/addAddress', {params:this.addCard}).then(function (res) {
                        // console.log(res)
                        if(res.body.messageCode=='200'){
                            layer.alert('添加成功')
                            this.isAlert=!this.isAlert;
                           this. addressList()
                        }else{
                            layer.alert(res.body.message)
                        }
                    }).catch(function (res) {
                       layer.alert('网络请求失败，请刷新！！！')
                    })
                }

            }else{
                layer.alert('请输入正确的手机号')
            }

        },
        //获取商品列表
        //获取地址蓝sktOrdersId
        getUrlParam: function(name, str) {
            var url;
            if (str) {
                url = str.split("?")[1];
            } else {
                url = window.location.search.replace("?", "");
            }
            url = url.split("&");
            var ret = {};
            url.forEach(function (o,i) {
                var d = o.split("=");
                ret[d[0]] = decodeURI(d[1]);
            });
            if (name)
                return ret[name];
            else
                return ret;
        },
        getProductList:function(){
            //判断本地数据是否有，如果有就用本地数据，没有就为[]
            var _this=this ,sktOrdersId=[];//||(JSON.parse(localStorage.orderId)) ;

            //判断地址蓝是否有值，有值就合并
            if(_this.getUrlParam('sktOrdersId')){

                sktOrdersId.push(parseInt(_this.getUrlParam('sktOrdersId')))
            }else{
                if(localStorage.orderId){
                    sktOrdersId=JSON.parse(localStorage.orderId)
                }
            }

            //便利当前的订单id，一个订单ID请求一次服务器
           sktOrdersId.forEach(function (val,index) {
                       _this.$http.get(SURL+'sktOrders/showOrdersGoodsLoad',{params:{sktOrdersId:val}}).then(function (res) {
                         //  console.log(res)
                          // _this.orderList=res.body.entity;
                          _this.orderList=  _this.orderList.concat(res.body.entity)

                           localStorage.setItem('orderIdList',JSON.stringify(_this.orderList));
                          //给对象赋值,留言赋值
                           _this.orderList.forEach(function (v,i) {
                            //  console.log(v)
                               if(typeof v.orderRemarks=='undefined'){
                                   _this.$set(v,'orderRemarks','')
                               }
                           });
                           //获取运费
                           //_this.getFreight()
                       })
           });
        },


        //点击获取地址详情

        getDetailAddress:function(item,i){
        var _this=this;
            _this.currentIndex=i;
            _this.clickCard= item;
            _this.finalCard=this.clickCard;
            _this.getFreight()
        },

        //获取运费
        //1 获取当前可选市区

        selectCity:function(){


        },
        getFreight:function(){

            var _this=this,cityid;

            var is = (function () {
                var isHasDefault = 0;
                console.log(_this.addList.length);

                if (_this.addList.length == 0) {
                    layer.alert('请添加地址.....');
                    // console.log(11)
                } else {
                    _this.addList.forEach(function (v, i) {

                        if (v.isDefault) {
                            isHasDefault += 1;
                            cityid = v.cityId;
                            _this.finalCard = _this.addList[i];
                            return false;
                        } else {
                            isHasDefault += 0;
                        }
                    });
                }
                return isHasDefault;
            })();
      // console.log(is())
                if(_this.clickCard.cityId!=undefined){
                    //添加最终地址
                    _this.finalCard=_this.clickCard;
                    cityid=_this.clickCard.cityId
                } else if(is==0){
                    layer.alert('请选择地址');

                }
                console.log(_this.finalCard)




            _this.getDefault();//获取当前的默认地址
            //获取当前的运费
            console.log(cityid);
            if(_this.addList.length!=0){
                _this.$http.get(SURL+'sktOrders/getFreight',{params:{shopIds:JSON.parse(localStorage.shopIdArr),cityId:cityid}}).then(function (res) {
                    _this.orderList.forEach(function (v,i) {
                        //console.log(v)
                        res.body.entity.forEach(function (val,index) {
                            if(v.shopId==val.shopId){
                                v.freight=val.freight;

                            }
                        })
                    })

                })
            }

            
        },
        //提交订单
        subOrder:function () {
            var _this=this,orderArr=[] ,toPayOrderId=[],newOrder=[];

            //console.log(_this.orderList);
            _this.orderList.forEach(function (v,i) {
                var  orderObj={};
                orderObj.orderRemarks=v.orderRemarks;
                orderObj.sktOrdersId=v.orderId;
                toPayOrderId.push(v.orderId);//去结算页面获取订单id
                orderArr.push(orderObj)
                newOrder.push(v.orderId)
            });
          //  console.log(_this.orderArr);
            var orderObj={
                param: JSON.stringify(orderArr),
                areaId:_this.finalCard.areaId,
                areaIdPath:_this.finalCard.provinceId+'_'+_this.finalCard.cityId+'_'+_this.finalCard.areaId,
                userName:_this.finalCard.userName,
                userAddress:_this.finalCard.provinceName+''+_this.finalCard.cityName+''+_this.finalCard.areaName+''+
                    _this.finalCard.userAddress,
                userPhone:_this.finalCard.userPhone,
                isInvoice:_this.billNum,
                invoiceClient:_this.invoiceClient,
                deliverMoney :  returnFloat(_this.defaulFreight)//运费
            };
                _this.$http.get(SURL+'/sktOrders/submitOrder',{params:orderObj}).then(function (res) {
                    if(res.body.messageCode=='200'){
                        location.href='../orderCompletion/orderCompletion.html?newOrder='+encodeURI(JSON.stringify(newOrder))
                    }
                });



        }


    },
});

// Vue.config.devtools = true
